package cn.db101.kaoqinserver.service;

import cn.db101.kaoqinserver.config.ApiResult;
import cn.db101.kaoqinserver.config.FacePropertiesConfig;
import cn.db101.kaoqinserver.domain.Check;
import cn.db101.kaoqinserver.domain.User;
import cn.db101.kaoqinserver.enumration.CheckType;
import cn.db101.kaoqinserver.mapper.UserMapper;
import cn.db101.kaoqinserver.model.FaceResult;
import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FaceService {

    @Autowired
    private AipFace aipFace;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CheckService checkService;

    public ApiResult faceCompare(Check check) {

        // 查询本地照片
        User localUser = userMapper.selectById(check.getUserId());
        // faceImage是url地址，转换成base64
        MatchRequest req1 = new MatchRequest(Base64.encode(HttpUtil.downloadBytes(check.getFaceImage())), "BASE64");
        MatchRequest req2 = new MatchRequest(Base64.encode(HttpUtil.downloadBytes(localUser.getFaceImage())), "BASE64");
        List<MatchRequest> requests = new ArrayList<>();
        requests.add(req1);
        requests.add(req2);

        JSONObject res = aipFace.match(requests);
        String result = res.toString(2);

        FaceResult faceResult = JSONUtil.toBean(result, FaceResult.class);

        // 状态码判断
        if (faceResult.getErrorMsg().equals("SUCCESS")) {
            if(faceResult.getResult().getScore() > 90) {
                // 签到插入
                check.setCheckType(CheckType.FACE.getCheckType());
                checkService.thirdSave(check);
                return ApiResult.ofSuccess();
            } else {
                return ApiResult.ofError(400, "非本人");
            }
        } else {
            return ApiResult.ofError(400, "未检测到目标人脸");
        }
    }

}
